package com.a.html5nfc.reader;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;

import com.a.plugin.reader.PluginReader;
import com.example.android.nfc.record.TextRecord;

public class ReadNfcActivity extends Activity {

	PluginReader plugReader;
	static final String TAG = "ReadNfcActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "activity created");
		super.onCreate(savedInstanceState);
		plugReader = new PluginReader();
		resolveIntent(this.getIntent());
	}

	void resolveIntent(Intent intent) {
		// Parse the intent
		Log.d(TAG, "got here");
		String action = intent.getAction();
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
			// When a tag is discovered we send it to the service to be save. We
			// include a PendingIntent for the service to call back onto. This
			// will cause this activity to be restarted with onNewIntent(). At
			// that time we read it from the database and view it.
			Parcelable[] rawMsgs = intent
					.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			NdefMessage[] msgs;
			if (rawMsgs != null) {
				msgs = new NdefMessage[rawMsgs.length];
				for (int i = 0; i < rawMsgs.length; i++) {
					msgs[i] = (NdefMessage) rawMsgs[i];
				}

				for (NdefRecord record : msgs[0].getRecords()) {
					// if(TextRecord.isText(record)) {
					// TextRecord text = TextRecord.parse(record);
					String payloadText = new String(record.getPayload());
					Log.d(TAG, payloadText);
					// Log.d(TAG, text.getText());

					// Send the text to phonegap
					//plugReader.execute(null, new JSONArray().put(payloadText),null);
					plugReader.sendJavascript("nfcData('"+ payloadText + "')");
					// }

				}

			} else {
				// Unknown tag type
				byte[] empty = new byte[] {};
				NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
						empty, empty, empty);
				NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
				msgs = new NdefMessage[] { msg };
			}
			// Setup the views

		} else {
			Log.e(TAG, "Unknown intent " + intent);
			finish();
			return;
		}

		this.finish();
	}

}
